package com.colin.distributelock.controller;

import com.colin.distributelock.domain.DistributeLock;
import com.colin.distributelock.mapper.DistributeLockMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * Created by Colin on 2020/8/30 15:11
 * email: colinzhaodong@gmail.com
 * desc:
 *
 * @author zhaod
 */
@RestController
@Slf4j
public class DemoController {
	@Resource
	private DistributeLockMapper distributeLockMapper;

	@Resource
	private RedisTemplate redisTemplate;
	//private final Lock lock = new ReentrantLock();
	//@RequestMapping("singleLock")
	//public String singleLock(){
	//	lock.lock();
	//	try {
	//		log.info("我进入了锁");
	//		TimeUnit.SECONDS.sleep(60);
	//	} catch (InterruptedException e) {
	//		e.printStackTrace();
	//	}finally {
	//		lock.unlock();
	//	}
	//	return "锁";
	//}

	@GetMapping("singlelock")
	@Transactional(rollbackFor = Exception.class)
	public String singleLock() throws Exception{
		log.info("我进入了方法");

		DistributeLock demo = distributeLockMapper.selectDistributeLock("demo");
		if (Objects.isNull(demo)){
			throw new Exception("分布式锁找不到");
		}
		log.info("我进入了锁");
		try {
			TimeUnit.SECONDS.sleep(60);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return "执行完成";
	}
}
